/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.thread

import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import org.slf4j.LoggerFactory

class TaomuThreadPoolFactory {
	val static LOG = LoggerFactory.getLogger(TaomuThreadPoolFactory);
	val static coreSize = Runtime.runtime.availableProcessors;
	var static ThreadPoolExecutor threadPool = null;
	var static ScheduledThreadPoolExecutor scheduledThreadPool = null;

	def static getThreadPool() {
		return threadPool;
	}

	def static getscheduledThreadPool(){
		return scheduledThreadPool;
	}

	def static init(int queueSize,String host) {
		LOG.info("设置的线程池队列大小为:{}",queueSize);
		var workQueue = new ArrayBlockingQueue<Runnable>(queueSize <= 0 ? coreSize : queueSize) // 指定一种队列 （有界队列）
		threadPool = new ThreadPoolExecutor(
			coreSize,
			coreSize,
			60,
			TimeUnit.SECONDS,
			workQueue,
			new TaomuRunsPolicy(host) // 自定义拒绝策略
		)
		scheduledThreadPool = new ScheduledThreadPoolExecutor(coreSize,new TaomuRunsPolicy(host));
		Runtime.runtime.addShutdownHook(new Thread() {
			override run() {
				LOG.info("关闭线程池");
				threadPool.shutdown();
				scheduledThreadPool.shutdown();
			}
		})
	}
}
